let express = require('express');
let path = require('path');
let app = module.exports = express();
let ejs = require('ejs');
let config = require('config');
let cookieParser = require('cookie-parser');
let connect_mongo = require('connect-mongo');
let session = require('express-session');
let mongoose = require('mongoose');

let MongoStore = connect_mongo(session);

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

app.use(require('morgan')('dev'));

let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./init');
// interceptor
require('./intercept')(app);
require('./routes')(app);
require('./models');

// log4js init
require('./log4js/initLog4js');
let log4js = require('log4js');
let logger = log4js.getLogger(__filename);

app.use(function (req, res, next) {
    console.log('---------------404------------------');
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development' || app.get('env') === 'test') {
    app.use(devErrCatchFunction);
} else {
    // production error handler
    app.use(productionErrCatchFunction);
}

if (app.get('env') !== 'test') {
    app.listen(process.env.PORT || config.port);
    console.log('listen --- ', process.env.PORT || config.port);
}

function devErrCatchFunction(err, req, res, next) {
    res.status(err.status || 500);
    // console.log('error on request %d %s %s', process.domain.id, req.method, req.url);
    // console.log(err.stack);
    logger.error('url -- ' + req.originalUrl);
    logger.error(err.message || (err.err && err.err.message) || JSON.stringify(err.errinfo) || JSON.stringify(err));
    // res.render('error', err).json(err);
    res.json(err);
}

function productionErrCatchFunction(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.errmsg,
        error: {}
    });
}